import {
  _decorator,
  Animation,
  Collider,
  Collider2D,
  Component,
  Contact2DType,
  Game,
  Input,
  input,
  Node,
  RigidBody2D,
  Vec2,
} from "cc";
import { GameElementType } from "./Contanst";
import { GameManager } from "./GameManager";
const { ccclass, property } = _decorator;

@ccclass("Bird")
export class Bird extends Component {
  @property
  public rotateSpeed = 60;

  private _canControl = true;

  protected onLoad(): void {
    const collider = this.getComponent(Collider2D);
    if (collider) {
      collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
      collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
    }

    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
  }
  protected onDestroy(): void {
    input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
  }

  protected start() {}

  protected update(deltaTime: number) {
    if (!this._canControl) return;
    this.node.angle -= this.rotateSpeed * deltaTime;
    if (this.node.angle <= -60) {
      this.node.angle = -60;
    }
  }

  public onTouchStart(): void {
    console.log("before touch start");
    if (!this._canControl) return;
    this.node.angle = 30;
    console.log("before touch start");
    this.node.getComponent(RigidBody2D).linearVelocity = new Vec2(0, 6);
    console.log("touch start");
  }

  public onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    if (
      otherCollider.tag == GameElementType.LAND ||
      otherCollider.tag == GameElementType.PIPE
    ) {
      //   this.disableTouch();
      GameManager.getInstance().switchOver();
      console.log("game over");
      return;
    }
  }

  public onEndContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    if (otherCollider.tag == GameElementType.PIPE_MIDDLE) {
      GameManager.getInstance().addScore();
      return;
    }
  }

  public enableBirdControl() {
    this.node.getComponent(Animation).enabled = true;
    this.node.getComponent(RigidBody2D).enabled = true;
    this._canControl = true;
  }

  public disableBirdControl() {
    this.node.getComponent(Animation).enabled = false;
    this.node.getComponent(RigidBody2D).enabled = false;
    this._canControl = false;
  }

  public disableBirdControlNoRigidBody() {
    this.node.getComponent(Animation).enabled = false;
    this._canControl = false;
  }
}
